<!--
 * @Author: Freude Xu
 * @Date: 2021-10-06 16:53:41
 * @LastEditors: Freude Xu
 * @LastEditTime: 2021-10-06 17:12:28
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>倒计时</title>
    <style>
        div {
            margin: 100px auto;
        }
        
        span {
            display: inline-block;
            width: 50px;
            height: 50px;
            background-color: black;
            color: white;
            font-size: 25px;
            line-height: 50px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        var hour = document.querySelector('.hour');
        var minute = document.querySelector('.minute');
        var second = document.querySelector('.second');
        //设定新时间
        var inputTime = +new Date('2021-10-07 00:00:00');
        //在一开始就先调用一次就不需要刷新后在进行调用
        countDown();
        setInterval(countDown, 1000);
        //获取事件差
        function countDown() {
            var nowTime = new Date();
            var times = (inputTime - nowTime) / 1000;
            var h = parseInt(times / 60 / 60 % 24);
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h;
            var m = parseInt(times / 60 % 60);
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60);
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>
</body>

</html>